﻿#region
// ----------------------------------------------------------------
// 文 件 名：LogHelper
// 描  述：
//
// 创建标识：
//
// 修改标识：
// 修改描述：
//
// 修改标识：
// 修改描述：
//
// 备  注：
// ----------------------------------------------------------------
#endregion

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using log4net;
using log4net.Config;

namespace WindowsSvc_Test
{
    public class LogHelper
    {

        /// <summary>
        /// 静态锁
        /// </summary>
        private static readonly object LockHelper = new object();

        /// <summary>
        /// 日志管理器
        /// </summary>
        private static ILog _log = null;


        /// <summary>
        /// 初始化日志管理器
        /// </summary>
        private static void Init()
        {
            //配置文件路径
            try
            {
                FileInfo configFile = new FileInfo(string.Format("{0}/Config/log4net.config", AppDomain.CurrentDomain.BaseDirectory));
                if (!configFile.Exists)
                {
                    CreateConfigFile(configFile);
                }
                XmlConfigurator.ConfigureAndWatch(configFile);
                _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
            }
            catch
            { }
        }

        /// <summary>
        /// 创建配置文件
        /// </summary>
        /// <param name="fileInfo">文件信息</param>
        private static void CreateConfigFile(FileInfo fileInfo)
        {
            using (StreamWriter sw = File.CreateText(fileInfo.FullName))
            {
                sw.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
                sw.WriteLine("<configuration>");
                sw.WriteLine("  <log4net>");
                sw.WriteLine("    <root>");
                sw.WriteLine("      <level value=\"ALL\"/>");
                sw.WriteLine("       <appender-ref ref=\"MyLogger_1\" />");
                sw.WriteLine("   </root>");
                sw.WriteLine("    <appender name=\"MyLogger_1\" type=\"log4net.Appender.RollingFileAppender\">");
                sw.WriteLine("      <param name=\"File\" value=\"Logs/log_\"/>");
                sw.WriteLine("      <param name=\"AppendToFile\" value=\"true\"/>");
                sw.WriteLine("      <param name=\"RollingStyle\" value=\"Composite\"/>");
                sw.WriteLine("      <param name=\"DatePattern\" value=\"yyyy-MM-dd&quot;.txt&quot;\"/>");
                sw.WriteLine("      <param name=\"MaximumFileSize\" value=\"3MB\"/>");
                sw.WriteLine("      <param name=\"MaxSizeRollBackups\" value=\"100\"/>");
                sw.WriteLine("      <param name=\"StaticLogFileName\" value=\"false\"/>");
                sw.WriteLine("      <lockingModel type=\"log4net.Appender.FileAppender+MinimalLock\" />");
                sw.WriteLine("      <layout type=\"log4net.Layout.PatternLayout\">");
                sw.WriteLine("        <param name=\"ConversionPattern\" value=\"[时间]:%d [级别]:%p [线程]:%t%n[内容]:%m%n%n\"/>");
                sw.WriteLine("      </layout>");
                sw.WriteLine("    </appender>");
                sw.WriteLine("  </log4net>");
                sw.WriteLine("</configuration>");
                sw.Close();
            }
        }

        public static ILog MyLog
        {
            get
            {
                lock (LockHelper)
                {
                    if (_log == null)
                        Init();
                }
                return _log;
            }
        }

        /// <summary>
        /// 致命的、毁灭性的(用户记录一些程序运行时出现的致命错误)
        /// </summary>
        /// <param name="message">日志摘要</param>
        public static void Fatal(string message)
        {
            Fatal(message, null);
        }

        /// <summary>
        /// 致命的、毁灭性的(用户记录一些程序运行时出现的致命错误)
        /// </summary>
        /// <param name="message">日志摘要</param>
        /// <param name="exception">异常</param>
        public static void Fatal(string message, Exception exception)
        {
            try
            {
                if (MyLog.IsFatalEnabled)
                {
                    MyLog.Fatal(message, exception);
                    //可以增加发送短信、邮件
                }
            }
            catch
            {
                // ignored
            }
        }
        /// <summary>
        /// 错误(用户记录一些程序运行时出现错误)
        /// </summary>
        /// <param name="message">日志摘要</param>
        public static void Error(string message)
        {
            try
            {
                Error(message, null);
            }
            catch
            {
                // ignored
            }
        }

        /// <summary>
        /// 错误(用户记录一些程序运行时出现错误)
        /// </summary>
        /// <param name="message">日志摘要</param>
        /// <param name="exception">异常</param>
        public static void Error(string message, Exception exception)
        {
            try
            {

                if (MyLog.IsErrorEnabled)
                {
                    MyLog.Error(message, exception);
                }

            }
            catch
            {
                // ignored
            }
        }

        /// <summary>
        /// 警告、注意、通知(用于记录一些需要引起注意问题)
        /// </summary>
        /// <param name="message">日志摘要</param>
        public static void Warn(string message)
        {
            try
            {
                Warn(message, null);
            }
            catch
            {
                // ignored
            }
        }

        /// <summary>
        /// 警告、注意、通知(用于记录一些需要引起注意问题)
        /// </summary>
        /// <param name="message">日志摘要</param>
        /// <param name="exception">异常</param>
        public static void Warn(string message, Exception exception)
        {
            try
            {
                if (MyLog.IsWarnEnabled)
                {
                    MyLog.Warn(message, exception);
                }
            }
            catch
            {
                // ignored
            }
        }

        /// <summary>
        /// 信息(用于记录一些辅助信息)
        /// </summary>
        /// <param name="message">日志摘要</param>
        public static void Info(string message)
        {
            try
            {
                Info(message, null);
            }
            catch
            {
                // ignored
            }
        }

        /// <summary>
        /// 信息(用于记录一些辅助信息)
        /// </summary>
        /// <param name="message">日志摘要</param>
        /// <param name="exception">异常</param>
        public static void Info(string message, Exception exception)
        {
            try
            {
                if (MyLog.IsInfoEnabled)
                {
                    MyLog.Info(message, exception);
                }
            }
            catch
            {
                // ignored
            }
        }

        /// <summary>
        /// 调试(用于记录一些调试时才需要记录的日志)
        /// </summary>
        /// <param name="message">日志摘要</param>
        public static void Debug(string message)
        {
            try
            {
                Debug(message, null);
            }
            catch
            {
                // ignored
            }
        }

        /// <summary>
        /// 调试(用于记录一些调试时才需要记录的日志)
        /// </summary>
        /// <param name="message">日志摘要</param>
        /// <param name="exception">异常</param>
        public static void Debug(string message, Exception exception)
        {
            try
            {
                if (MyLog.IsDebugEnabled)
                {
                    MyLog.Debug(message, exception);
                }
            }
            catch
            {
                // ignored
            }
        }


    }

    /// <summary>
    /// 日志文件管理
    /// </summary>
    public class LoggerFileMgr
    {
        /// <summary>
        /// 删除日志,在每天的晚上22点到23点进行，删除在10天前写的文件
        /// </summary>
        public static void ClearLogFiles()
        {
            while (true)
            {
                try
                {
                    if ((DateTime.Now.Hour >= 22 && DateTime.Now.Hour <= 23) == false)
                    {
                        System.Threading.Thread.Sleep(100000);
                        continue;
                    }
                    string executablePath = System.Windows.Forms.Application.ExecutablePath;                    //启动了应用程序的可执行文件的路径，包括可执行文件的名称
                    string executableFolder = executablePath.Substring(0, executablePath.LastIndexOf('\\'));    //.exe文件所在的目录
                    DeleteFiles(string.Format("{0}\\{1}", executableFolder, "Logs\\"), DateTime.Now.AddDays(-10));
                    System.Threading.Thread.Sleep(100000);
                }
                catch
                { }
                finally
                {
                    System.Threading.Thread.Sleep(1000);
                }
            }
        }

        /// <summary>
        /// 物理删除某时间点之前的日志文件
        /// </summary>
        /// <param name="strFolder"></param>
        /// <param name="date"></param>
        public static void DeleteFiles(string strFolder, DateTime date)
        {
            try
            {
                DirectoryInfo dir = new DirectoryInfo(strFolder);
                FileInfo[] files = dir.GetFiles();
                if (files == null || files.Length <= 0)
                    return;
                for (int i = 0; i < files.Length; i++)
                {
                    if (files[i].LastWriteTime <= date)
                        files[i].Delete();
                }
            }
            catch
            {
                // ignored
            }
        }
    }

    public class MyLog
    {
        private string path = "";
        public MyLog(string path)
        {
            this.path = path;
        }
        public void Info(object msg)
        {
            using (StreamWriter sw = new StreamWriter(path, true))
            {
                sw.WriteLine(msg);
            }
        }
    }

}
